
from pao_python.pao.data import process_db,string_to_date
import datetime
import calendar
import json
import requests
import re
import uuid



def getMonthFirstDayAndLastDay(year=None, month=None):
    """
    :param year: 年份，默认是本年，可传int或str类型
    :param month: 月份，默认是本月，可传int或str类型
    :return: firstDay: 当月的第一天，datetime.date类型
              lastDay: 当月的最后一天，datetime.date类型
    """
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year

    if month:
        month = int(month)
    else:
        month = datetime.date.today().month

    # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)

    # 获取当月的第一天
    firstDay = datetime.date(year=year, month=month, day=1).strftime('%Y-%m-%d')
    lastDay = datetime.date(year=year, month=month, day=monthRange).strftime('%Y-%m-%d')

    return {'first':firstDay, 'last':lastDay}

# def get_cur_year():
#     year = datetime.date.today().year
#     return year

def get_cur_month():
    month = datetime.date.today().month
    return month


def find_data(db,cols_name,data):
    cols = db[cols_name]
    return list(cols.find(data)[:])

def insert_data(db,cols_name,data):
    cols = db[cols_name]
    print(cols_name,'表插入成功')
    return cols.insert_one(data).inserted_id != ''

def update_data(db,cols_name,data,condfidition):
    cols = db[cols_name]
    print(cols_name,'表更新成功')
    # print(cols.update_one(condfidition,{'$set':data}).modified_count,'更新结果')
    return cols.update_one(condfidition,{'$set':data}).modified_count == 1
def delete_data(db,cols_name,confidition):
    cols = db[cols_name]
    print(cols_name,'表删除成功')
    return cols.delete_many(confidition).deleted_count > 0

def get_condition(condition):

    for key in list(condition.keys()):
        if not condition.get(key):
            del condition[key]
        else:
            if key in ['handle_code','handle_name']:
                new_handle_name = re.compile(condition[key])
                condition[key] = new_handle_name
            if key == 'create_date':
                start = string_to_date(condition[key]+' 00:00:00')
                date = {'$gte':start,'$lt': start+ datetime.timedelta(days=1)}
                # date = string_to_date_only(condition[key])
                condition[key] = date

    return condition



# def get_company_info(data):
#     dict_company = {'opera_type':False}
#     if 'id' not in data.keys():
#         dict_company['opera_type'] = True
#         data['id'] = str(uuid.uuid())
#         data['create_date'] = 
#     return {**dict_company,**data}
# def get_dict(data):
#     respCmtJson = re.sub(r"(,?)(\w+?)\s+?:", r"\1'\2' :", data)
#     respCmtJson = respCmtJson.replace("'", "\"")
#     cmtDict = json.loads(respCmtJson)
#     return cmtDict
    